package com.jhz.speedy.common.base;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

/**
 * FragmentPagerAdapter 基类
 *
 * Created by 均合 on 2017/1/19.
 */

public class BasePagerAdapter extends PagerAdapter {

    private ArrayList<View> views;

    public BasePagerAdapter(){
        updateList(null);
    }

    /**
     * 直接传view
     * @param views
     */
    public BasePagerAdapter(ArrayList<View> views) {
        updateList(views);
    }

    /**
     *
     * @param pagerCount    个数
     * @param onCreateItemListeners view创建
     */
    public BasePagerAdapter(int pagerCount, IOnCreateItemListeners onCreateItemListeners){
        updateList(pagerCount, onCreateItemListeners);
    }


    public void updateList(ArrayList<View> views){
        if(views == null){
            this.views = new ArrayList<>();
        }else {
            this.views = views;
        }
        notifyDataSetChanged();
    }

    /**
     * 初始化子视图
     * @param pagerCount    页数
     * @param onCreateItemListeners   初始子页化监听器
     */
    public void updateList(int pagerCount, IOnCreateItemListeners onCreateItemListeners) {
        ArrayList<View> views = new ArrayList<>();
        View itemView;
        for(int i = 0; i < pagerCount; i++){
            itemView = onCreateItemListeners.onCreateItem(i);
            views.add(itemView);
        }
        updateList(views);
    }

    @Override
    public int getCount() {
        return views.size();
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public int getItemPosition(Object object) {
        // TODO Auto-generated method stub
        //		return super.getItemPosition(object);
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(views.get(position));
        return views.get(position);
    }

    /**
     * 初始化item监听器
     */
    public interface IOnCreateItemListeners {
        /**
         * 初始化视图
         * @param index 第几项
         */
        View onCreateItem(int index);
    }
}
